//
//  VIPOrderDetail.swift
//  LeGou
//
//  Created by lxm on 2022/8/5.
//

import UIKit
import RxSwift

class VIPOrderDetail: ZMViewController {
    //MARK: --------------------属性--------------------
    var orderNo = ""
    
    var orderInfo = ZMUtil.fastNilBehavior(type: VIPMallModels.OrderDetial.self)
    
    let timer = Observable<Int>.timer(.seconds(0), period: .milliseconds(10), scheduler: MainScheduler.instance)
    
    var timerDisposeBag = DisposeBag()
    
    var bindDisposeBag = DisposeBag()
    
    var currentAddress = ZMUtil.fastNilBehavior(type: AddressModel.self)


//    var paychecker : PayChecker<String> = PayChecker()
//    // 0 微信 1 支付宝
//    var payType = 0
    
    let payHelper = PayHelper()
    //MARK: --------------------UI控件--------------------
    let nav = NavigationBarView()
    
    let scrollView = UIScrollView()

    let scrollContent = ZMUtil.stackView(axis: .vertical, spacing: 8)

    let bgView = UIView().then({$0.backgroundColor = Style.mainColor})
    
    let scrollBgView = UIView().then({$0.backgroundColor = Style.mainColor})

    // 状态背景
    let stateBg = ZMUtil.imageView(imageName: "order_time_bg")
    
    let header = OrderDetailHeaderView()
    
    let addresss = OrderDetailAddressView()
    
    // 商品信息
    let goodsView = OrderDetailGoodsView()
    
    let info = DetailInfoView()
    
    let bottomView = UIView().then({$0.backgroundColor = .white})
    
    let leftButton = UIButton()
    
    let rightButton = UIButton()
    
    let loading = XMLoadingView()
    
    // 竞拍新加
    let jpContent = UIView().then({$0.backgroundColor = .white})
    let jpDesLabel = ZMUtil.label(title: "竞购实际获得：", color: UIColor.zm.color333333(), font: UIFont.systemFont(ofSize: 12))
    let jpDetail = ZMUtil.label(title: "商品", color: UIColor.zm.color333333(), font: UIFont.systemFont(ofSize: 12, weight: .medium))

    //MARK: --------------------生命周期--------------------
    override func viewDidLoad() {
        super.viewDidLoad()
        setUI()
        addConstraints()
        bindAction()
        loading.showInView(fatherView: view)
        loadDetail()
    }
    
    //MARK: --------------------UI--------------------
    func setUI() {
        hbd_barHidden = true
        view.addSubview(bgView)
        
        view.addSubview(nav)
        nav.autoBack = true
        
        view.addSubview(scrollView)
        
        scrollView.addSubview(scrollBgView)
        
        scrollView.addSubview(stateBg)
        
        scrollView.addSubview(scrollContent)
        
        scrollContent.addArrangedSubview(header)
        
        scrollContent.addArrangedSubview(addresss)
        
        scrollContent.addArrangedSubview(goodsView)
        
        scrollContent.addArrangedSubview(jpContent)
        
        scrollContent.addArrangedSubview(info)
        
        scrollView.backgroundColor = "#F5F5F5".zm.hex()
        
        info.info = [
            ("订单编号：", "1728479087637478", nil),
            ("下单时间：", "1728479087637478", nil),
            ("订单金额：", "￥299", "#DE3F26".zm.hex())
        ]
            
        view.addSubview(bottomView)
        
        // bottom button
        setBottomButtonStyle(leftButton, 0, "联系客服")
        setBottomButtonStyle(rightButton, 1, "确认收货")
        
        let stack = ZMUtil.stackView(axis: .horizontal, spacing: 12)
        stack.addArrangedSubview(leftButton)
        stack.addArrangedSubview(rightButton)
        bottomView.addSubview(stack)
        stack.snp.makeConstraints { make in
            make.centerY.equalToSuperview()
            make.right.equalToSuperview().offset(-16)
        }
        
//        paychecker.delegate = self
        
        jpContent.addSubview(jpDesLabel)
        jpContent.addSubview(jpDetail)

    }
    
    func addConstraints() {
        scrollBgView.snp.makeConstraints { make in
            make.left.right.top.equalToSuperview()
            make.height.equalTo(170)
        }
        nav.snp.makeConstraints { make in
            make.top.right.left.equalToSuperview()
        }
        
        scrollView.snp.makeConstraints { make in
            make.top.equalTo(nav.snp.bottom)
            make.left.bottom.right.equalToSuperview()
        }
        
        scrollContent.snp.makeConstraints { make in
            make.edges.equalToSuperview()
            make.centerX.equalToSuperview()
        }
        
        bgView.snp.makeConstraints { make in
            make.top.left.right.equalToSuperview()
            make.height.equalTo(400)
        }
        
        stateBg.snp.makeConstraints { make in
            make.right.equalToSuperview()
            make.top.equalToSuperview().offset(20)
        }
        
        bottomView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.height.equalTo(56)
            make.bottom.equalTo(self.view.safeAreaLayoutGuide.snp.bottom)
        }
        
        jpContent.snp.makeConstraints { make in
            make.height.equalTo(49)
        }
        
        jpDesLabel.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(16)
            make.centerY.equalToSuperview()
        }
        
        jpDetail.snp.makeConstraints { make in
            make.left.equalTo(jpDesLabel.snp.right).offset(8)
            make.centerY.equalToSuperview()
        }
    }
    
    //MARK: --------------------methods--------------------
    func bindAction() {
        
//        leftButton.rx.tap.subscribe(onNext:{ [unowned self] resp in
//            let v = ZMUtil.loadNibViewFullScreen(nibName: ServiceWx.self)
//            APPWindow?.addSubview(v)
//        }).disposed(by: disposeBag)
        
        _ = addresss.zm.addTapGestureRecognizer(target: self, action: #selector(selectAddress))
        
        header.payButton.rx.tap.subscribe(onNext:{ [unowned self] resp in
            guard let info = orderInfo.value else {return}
            let payPrice = info.orderType == .integral ? "\(info.payIntegral.zm.toString(keep: 2))" : "\(info.payPrice.zm.toString(keep: 2))"
            self.showPay(info.orderId, money: payPrice)
        }).disposed(by: disposeBag)
        
        

        orderInfo.subscribe(onNext:{ [unowned self] resp in
            guard let resp = resp else {return}
            self.bindDisposeBag = DisposeBag()
            let isIntegral = resp.orderType == .integral
            self.addresss.noaddressView.isHidden = true
            let payPrice = isIntegral ? "\(resp.payIntegral.zm.toString(keep: 2))积分" : "￥\(resp.payPrice.zm.toString(keep: 2))"
            switch resp.showStatus {
                case .unpay:
                self.header.statusLabel.text = "等待\(isIntegral ? "兑换" : "付款")"
                    self.header.statusIcon.image = UIImage.init(named: "order_time_icon")
                    self.setTimerTitle()
                self.header.payButton.setTitle("去\(isIntegral ? "兑换" : "支付")", for: .normal)
                    // timer
                    self.goTimer()
                
                info.info = [
                    ("订单编号：", resp.orderId, nil),
                    ("下单时间：", resp.createTime, nil),
                    ("订单金额：", payPrice, "#DE3F26".zm.hex())
                ]
                
                self.rightButton.isHidden = false
                self.leftButton.setTitle("取消订单", for: .normal)
                self.leftButton.rx.tap.subscribe(onNext:{ [unowned self] r in
                    self.cancelOrder(id: resp.id)
                }).disposed(by: self.bindDisposeBag)
                
                self.rightButton.layer.borderWidth = 0
                self.rightButton.backgroundColor = Style.mainColor
                self.rightButton.setTitle("立即\(isIntegral ? "兑换" : "付款")", for: .normal)
                self.rightButton.setTitleColor(.white, for: .normal)
                self.rightButton.rx.tap.subscribe(onNext:{ [unowned self] r in
                    let payPrice = resp.orderType == .integral ? "\(resp.payIntegral.zm.toString(keep: 2))" : "\(resp.payPrice.zm.toString(keep: 2))"
                    self.showPay(resp.orderId, money: payPrice)
                }).disposed(by: self.bindDisposeBag)
            case .waitConfirm:
                self.addresss.noaddressView.isHidden = false
                self.header.statusLabel.text = "待确认"
                self.header.statusIcon.image = UIImage.init(named: "order_time_icon")
                self.header.subTitle.text = "请确认收货地址"
                self.header.hidePayButton()
                info.info = [
                    ("订单编号：", resp.orderId, nil),
                    ("下单时间：", resp.createTime, nil),
                    ("订单金额：", payPrice, "#DE3F26".zm.hex())
                ]
                
                self.rightButton.isHidden = false
                self.leftButton.isHidden = true
                
                self.rightButton.layer.borderWidth = 0
                self.rightButton.backgroundColor = Style.mainColor
                self.rightButton.setTitle("确认收货地址", for: .normal)
                self.rightButton.setTitleColor(.white, for: .normal)
                self.rightButton.rx.tap.subscribe(onNext:{ [unowned self] r in
                    self.selectAddress()
                }).disposed(by: self.bindDisposeBag)
                
            case .waitSend:
                // 待发货
                self.header.statusLabel.text = "等待发货"
                self.header.statusIcon.image = UIImage.init(named: "order_car")
                self.header.hidePayButton()
                self.header.subTitle.text = "正在出库中..."
                
                if resp.orderType == .compound {
                    info.info = [
                        ("订单编号：", resp.orderId, nil),
                        ("下单时间：", resp.createTime, nil),
                        ("订单金额：", payPrice, "#DE3F26".zm.hex()),
                    ]
                } else {
                    info.info = [
                        ("订单编号：", resp.orderId, nil),
                        ("下单时间：", resp.createTime, nil),
                        ("支付方式：", resp.payTypeStr, nil),
                        ("支付时间：", resp.payTime, nil),
                        ("订单金额：", payPrice, "#DE3F26".zm.hex()),
                    ]
                }
                
                self.rightButton.isHidden = true
                self.leftButton.setTitle("联系客服", for: .normal)
                self.leftButton.rx.tap.subscribe(onNext:{ [unowned self] r in
                    CommonService.shared.showContactService()
                }).disposed(by: self.bindDisposeBag)
                
            case .waitReceive:
                // 待收货
                self.header.statusLabel.text = "等待收货"
                self.header.statusIcon.image = UIImage.init(named: "order_box")
                self.header.hidePayButton()
                self.header.subTitle.text = "加油运输中..."
                
                if resp.orderType == .compound {
                    info.info = [
                        ("订单编号：", resp.orderId, nil),
                        ("下单时间：", resp.createTime, nil),
                        ("订单金额：", payPrice, "#DE3F26".zm.hex()),
                    ]
                } else {
                    info.info = [
                        ("订单编号：", resp.orderId, nil),
                        ("下单时间：", resp.createTime, nil),
                        ("支付方式：", resp.payTypeStr, nil),
                        ("支付时间：", resp.payTime, nil),
                        ("订单金额：", payPrice, "#DE3F26".zm.hex()),
                    ]
                }
                                
                self.rightButton.isHidden = false
                if resp.orderType == .lesson {
                    self.leftButton.setTitle("查看课程", for: .normal)
                    self.leftButton.rx.tap.subscribe(onNext:{ [unowned self] r in
                        self.showTheLesson(downloadLink: resp.downloadLink, password: resp.password)
                    }).disposed(by: self.bindDisposeBag)
                } else {
                    self.leftButton.setTitle("查看物流", for: .normal)
                    self.leftButton.rx.tap.subscribe(onNext:{ [unowned self] r in
                        self.goExpress(resp.orderId)
                    }).disposed(by: self.bindDisposeBag)
                }
                
                
                self.rightButton.layer.borderWidth = 0
                self.rightButton.backgroundColor = Style.mainColor
                self.rightButton.setTitle("确认收货", for: .normal)
                self.rightButton.setTitleColor(.white, for: .normal)
                self.rightButton.rx.tap.subscribe(onNext:{ [unowned self] r in
                    self.ensureReceive(id: resp.id)
                }).disposed(by: self.bindDisposeBag)
                
            case .complete:
                // 完成
                self.header.statusLabel.text = "完成"
                self.header.statusIcon.image = UIImage.init(named: "order_gou")
                self.header.hidePayButton()
                self.header.subTitle.text = "已完成订单"
                
                if resp.orderType == .auction {
                    info.info = [
                        ("订单编号：", resp.orderId, nil),
                        ("下单时间：", resp.createTime, nil),
                        ("支付方式：", resp.payTypeStr, nil),
                        ("支付时间：", resp.payTime, nil),
                        ("订单金额：", payPrice, "#DE3F26".zm.hex()),
                    ]
                } else if resp.orderType == .compound {
                    info.info = [
                        ("订单编号：", resp.orderId, nil),
                        ("下单时间：", resp.createTime, nil),
                        ("订单完成时间：", resp.takeTime, nil),
                        ("订单金额：", payPrice, "#DE3F26".zm.hex()),
                    ]
                } else {
                    info.info = [
                        ("订单编号：", resp.orderId, nil),
                        ("下单时间：", resp.createTime, nil),
                        ("支付方式：", resp.payTypeStr, nil),
                        ("支付时间：", resp.payTime, nil),
                        ("订单完成时间：", resp.takeTime, nil),
                        ("订单金额：", payPrice, "#DE3F26".zm.hex()),
                    ]
                }
                
                
                self.rightButton.isHidden = false
                
                if resp.orderType == .lesson {
                    self.leftButton.setTitle("查看课程", for: .normal)
                    self.leftButton.rx.tap.subscribe(onNext:{ [unowned self] r in
                        self.showTheLesson(downloadLink: resp.downloadLink, password: resp.password)
                    }).disposed(by: self.bindDisposeBag)
                } else {
                    self.leftButton.setTitle("联系客服", for: .normal)
                    self.leftButton.rx.tap.subscribe(onNext:{ [unowned self] r in
                        CommonService.shared.showContactService()
                    }).disposed(by: self.bindDisposeBag)
                }
                
                self.rightButton.layer.borderWidth = 0.5
                self.rightButton.backgroundColor = .white
                self.rightButton.setTitle("删除订单", for: .normal)
                self.rightButton.setTitleColor(UIColor.zm.color333333(), for: .normal)
                self.rightButton.layer.borderColor = UIColor.zm.colorCCCCCC().cgColor
                self.rightButton.rx.tap.subscribe(onNext:{ [unowned self] r in
                    self.ensureDelete(id: resp.id)
                }).disposed(by: self.bindDisposeBag)
            }
            
            // address
            if resp.showStatus != .waitConfirm {
                let addremodel = AddressModel()
                addremodel.realName = resp.realName
                addremodel.phone = resp.userPhone
                addremodel.detail = resp.userAddress
                self.currentAddress.accept(addremodel)
            }
            
            if resp.orderType == .auction {
                // 竞拍订单
                self.jpContent.isHidden = false
                self.jpDetail.text = resp.giveType == 0 ? "商品" : "积分"
                self.goodsView.showActivity(true, value: resp.gainActivity.zm.toString(keep: 4))
                self.goodsView.price.text = resp.totalPrice.zm.toString(keep: 2)
                self.goodsView.layoutSubviews()
            } else if resp.orderType == .integral {
                // 积分订单
                self.jpContent.isHidden = true
                self.goodsView.showActivity(resp.gainActivity > 0, value: resp.gainActivity.zm.toString(keep: 4))
                self.goodsView.unit.isHidden = true
                self.goodsView.price.text = resp.payIntegral.zm.toString(keep: 2) + "积分"
            } else if resp.orderType == .compound {
                self.jpContent.isHidden = true
                self.goodsView.showActivity(false, value: "")
                self.goodsView.price.text = resp.orderInfoList[0].price.zm.toString(keep: 2)
                self.goodsView.topleftIcon.isHidden = false
            } else {
                self.jpContent.isHidden = true
                self.goodsView.showActivity(false, value: "")
                self.goodsView.price.text = resp.orderInfoList[0].price.zm.toString(keep: 2)
            }
            // goodsView
            self.goodsView.img.zm.setImage(urlStr: resp.orderInfoList[0].image)
            self.goodsView.name.text = resp.orderInfoList[0].storeName
            self.goodsView.num.text = "数量：\(resp.orderInfoList[0].cartNum)"
            
            if resp.orderType == .vipMall {
                self.goodsView.titleBtn.setTitle("创客优选商城", for: .normal)
                self.goodsView.titleBtn.setImage(UIImage.init(named: "order_home_icon"), for: .normal)
            } else if resp.orderType == .lesson {
                self.goodsView.titleBtn.setTitle("知识付费", for: .normal)
                self.goodsView.titleBtn.setImage(UIImage.init(named: "order_money_icon"), for: .normal)
            } else if resp.orderType == .selfMall {
                self.goodsView.titleBtn.setTitle("自营商城", for: .normal)
                self.goodsView.titleBtn.setImage(UIImage.init(named: "order_home_icon"), for: .normal)
            } else if resp.orderType == .integral {
                self.goodsView.titleBtn.setTitle("积分兑换", for: .normal)
                self.goodsView.titleBtn.setImage(UIImage.init(named: "order_home_icon"), for: .normal)
            } else if resp.orderType == .auction {
                self.goodsView.titleBtn.setTitle("趣味竞购", for: .normal)
                self.goodsView.titleBtn.setImage(UIImage.init(named: "auction_hammer_black"), for: .normal)
            } else if resp.orderType == .compound {
                self.goodsView.titleBtn.setTitle("竞购合成", for: .normal)
                self.goodsView.titleBtn.setImage(UIImage.init(named: "order_compound"), for: .normal)
            }
            
            // detail
            
        }).disposed(by: disposeBag)
        
        ZMPayManager.shard.payCallBack.subscribe(onNext:{ [unowned self] resp in
            switch resp {
            case .success:
                // 支付成功
                self.loadDetail()
                break
            default:
                ZMToast.showToast(title: resp.rawValue)
            }
        }).disposed(by: disposeBag)
        
        payHelper.paySuccess = { [weak self] in
            guard let self = self else {return}
            self.loadDetail()
            ZMNotification.shard.subject.onNext(.refreshOrderList)
        }
        
        currentAddress.subscribe(onNext:{ [unowned self] resp in
            if let resp = resp {
                addresss.noaddressView.isHidden = true
                // address
                self.addresss.name.setTitle(resp.realName + " " + resp.phone , for: .normal)
                self.addresss.detail.text = "地址：\(resp.area + resp.detail)"
            } else {
                addresss.noaddressView.isHidden = false
            }
        }).disposed(by: disposeBag)
    }
    // 显示课程详情
    func showTheLesson(downloadLink : String, password : String) {
        let v = ZMUtil.loadNibViewFullScreen(nibName: LessonDetailView.self)
        v.downloadLink = downloadLink
        v.password = password
        v.resetUI()
        APPWindow?.addSubview(v)
    }
    
    @objc func selectAddress() {
        guard let a = orderInfo.value, a.showStatus == .waitConfirm else {return}
        let vc = ZMAddressListVC()
        vc.chooseAddressBlockNopush = { [unowned self] address in
            ZMAlertView.show(title: "提示", content: "您是否确认选择该收货地址？", left: "取消", right: "确认") {
                
            } onRight: {
                self.navigationController?.popViewController(animated: true)
                self.currentAddress.accept(address)
                self.onSureAddress()
            }
        }
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
    func goTimer() {
        timerDisposeBag = DisposeBag()
        timer.subscribe(onNext:{ [unowned self] resp in
            self.setTimerTitle()

        }).disposed(by: timerDisposeBag)
    }
    
    // 设置倒计时的文字
    func setTimerTitle() {
        guard let model = self.orderInfo.value, let r = model.timeDiss() else {return}
        if r.h == 0, r.m == 0, r.s <= 0 {
            // 时间读完
            self.navigationController?.popViewController(animated: true)
            ZMNotification.shard.subject.onNext(.refreshOrderList)
            return
        }
        let payPrice = model.orderType == .integral ? "\(model.payIntegral.zm.toString(keep: 2))积分" : "￥\(model.payPrice.zm.toString(keep: 2))"
        self.header.subTitle.text = "需付款：\(payPrice)  剩余：\(r.h)小时\(r.m)分钟"
    }
    
    func loadDetail() {
        VIPMallAPI.orderDetial(orderNo).rxRequest(type: VIPMallModels.OrderDetial.self).subscribe(onNext:{ [unowned self] resp in
            self.loading.hideView(anmation: true)
            self.orderInfo.accept(resp)
        }, onError: { e in
            self.loading.showError(e.localizedDescription)
        }).disposed(by: disposeBag)
    }
    
    func setBottomButtonStyle(_ button : UIButton, _ type : Int, _ title : String) {
        button.titleLabel?.font = UIFont.systemFont(ofSize: 14)
        button.layer.cornerRadius = 16
        button.snp.remakeConstraints { make in
            make.height.equalTo(32)
        }
        button.contentEdgeInsets = UIEdgeInsets(top: 0, left: 16, bottom: 0, right: 16)
        button.setTitle(title, for: .normal)

        if type == 0 {
            button.layer.borderWidth = 0.5
            button.layer.borderColor = "#CCCCCC".zm.hex().cgColor
            button.backgroundColor = .white
            button.setTitleColor(UIColor.zm.color333333(), for: .normal)
        } else {
            button.layer.borderWidth = 0
            button.backgroundColor = Style.mainColor
            button.setTitleColor(.white, for: .normal)
        }
    }
    
    func cancelOrder(id : Int) {
        ZMAlertView.show(title: "提示", content: "是否要取消当前订单", left: "否", right: "是") {
            
        } onRight: {
            ZMToast.showActivity()
            VIPMallAPI.cancelOrder(["id" : id]).rxRequestNullAble(type: [String : Any].self).subscribe(onNext:{ [unowned self] resp in
                ZMToast.hiddenActivity()
                self.navigationController?.popViewController(animated: true)
                ZMNotification.shard.subject.onNext(.refreshOrderList)
            }).disposed(by: self.disposeBag)
        }
    }
    
    func showPay(_ orderNo : String, money : String) {
        guard let info = orderInfo.value else {return}
        if info.orderType == .integral {
            self.payHelper.sendPay(currentVC: self, orderNo: orderNo, payType: .integral, info: PwdInputInfo(title: "请输入交易密码", money: money , left: "", right: "", type: 1)) { ok in
                if ok {

                }
            }
        } else {
            let v = ZMUtil.loadNibViewFullScreen(nibName: OrderChoosePayView.self)
            v.payMoney = Double(money) ?? 0
            v.price.text = money
            v.onPayCallback = { [weak self, weak v] type in
                guard let v = v, let self = self else {return}
                
                self.payHelper.sendPay(currentVC: self, orderNo: orderNo, payType: type, info: PwdInputInfo(money: money, left: "", right: "")) { ok in
                    if ok {
                        v.removeFromSuperview()
                    }
                }
            }
            v.onGetwalleted = { [weak self, weak v] in
                guard let v = v, let self = self else {return}
                if info.orderType == .autoRefund {
                    v.normalContent.isHidden = true
                    v.ckContent.isHidden = true
                }
            }
            APPWindow?.addSubview(v)
        }
    }
    
    func sendPay(pa : [String : Any], orderNo : String, payType : String, complete:@escaping (_ ok : Bool)->()) {
        VIPMallAPI.payInfo(pa).rxRequest(type: [String : Any].self).subscribe(onNext:{ [unowned self] resp in
            if payType == "yue" || payType == "mallYue" {
                // 支付成功
                self.loadDetail()
            } else {
                let payStr = JSON(resp)["alipayRequest"].stringValue
                if payType == "weixin" {
                    ZMPayManager.shard.wechatPay(resp, orderNum: orderNo)
                } else {
                    ZMPayManager.shard.aliPayWithInfo(payStr, orderNum: orderNo)
                }
//                self.payType = payType == "weixin" ? 0 : 1
//                self.paychecker.checkData.accept(orderNo)
//                self.paychecker.startCheck()
            }
            complete(true)
        }, onError: { _ in
            complete(false)
        }).disposed(by: self.disposeBag)
    }
    
    // 跳转查看物流
    func goExpress(_ orderNo : String) {
        let vc = ZMLogisticsVC()
        vc.orderNo = orderNo
        navigationController?.pushViewController(vc, animated: true)
    }
    
    func onSureAddress() {
        // 确认收货地址
        guard let a = currentAddress.value, let info = orderInfo.value else {
            ZMToast.showToast(title: "请选择收货地址")
            return
        }
        ZMToast.showActivity()
        VIPMallAPI.ensureAddress(["addressId" : a.id, "orderId" : info.orderId]).rxRequestNullAble(type: Any.self).subscribe(onNext:{ [unowned self] resp in
            ZMToast.hiddenActivity()
            self.loadDetail()
            ZMNotification.shard.subject.onNext(.refreshOrderList)
        }).disposed(by: disposeBag)
    }
    
    //  确认收货
    func ensureReceive(id : Int) {
        ZMAlertView.show(title: "提示", content: "是否确认收货", left: "否", right: "是") {
            
        } onRight: {
            ZMToast.showActivity()
            VIPMallAPI.suerReceive(id).rxRequestNullAble(type: [String : Any].self).subscribe(onNext:{ [unowned self] resp in
                ZMToast.hiddenActivity()
                self.loadDetail()
                ZMNotification.shard.subject.onNext(.refreshOrderList)
            }).disposed(by: self.disposeBag)
        }
    }

    //  删除订单
    func ensureDelete(id : Int) {
        ZMAlertView.show(title: "提示", content: "是否要删除当前订单", left: "否", right: "是") {
            
        } onRight: {
            ZMToast.showActivity()
            VIPMallAPI.deleteOrder(id).rxRequestNullAble(type: [String : Any].self).subscribe(onNext:{ [unowned self] resp in
                ZMToast.hiddenActivity()
                self.navigationController?.popViewController(animated: true)
                ZMNotification.shard.subject.onNext(.refreshOrderList)
            }).disposed(by: self.disposeBag)
        }
    }
    //MARK: --------------------delegate--------------------
}


class DetailInfoView : UIView  {
    var labelSpace : CGFloat = 8
    
    var info = [(title : String, content : String, contentColor : UIColor?)]() {
        didSet {
            updateUI()
        }
    }
    
    var stackView : UIStackView?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setUI()
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        setUI()
    }
    
    func setUI() {
        backgroundColor = .white
        updateUI()
    }
    
    func updateUI() {
        stackView?.removeFromSuperview()
        stackView = UIStackView()
        guard let stackView = stackView else {return}
        stackView.axis = .vertical
        stackView.spacing = 8
        for item in info {
            let v = UIView()
            let leftLabel = ZMUtil.label(title: item.0, color: "333333".zm.hex(), font: UIFont.systemFont(ofSize: 12, weight: .regular))
            let rightLabel = ZMUtil.label(title: item.1, color: item.2 ?? "333333".zm.hex(), font: UIFont.systemFont(ofSize: 12, weight: .medium))
            rightLabel.textAlignment = .left
            v.addSubview(leftLabel)
            v.addSubview(rightLabel)
            rightLabel.numberOfLines = 8
            rightLabel.setContentHuggingPriority(.defaultLow, for: .horizontal)
            rightLabel.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
            leftLabel.snp.makeConstraints { make in
                make.left.top.equalToSuperview()
                make.bottom.lessThanOrEqualToSuperview()
            }
            rightLabel.snp.makeConstraints { make in
                make.right.top.equalToSuperview()
                make.left.equalTo(leftLabel.snp.right).offset(labelSpace)
                make.bottom.equalToSuperview()
            }
            stackView.addArrangedSubview(v)
        }
        addSubview(stackView)
        stackView.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(12)
            make.left.equalToSuperview().offset(16)
            make.right.equalToSuperview().offset(-16)
            make.bottom.equalToSuperview().offset(-12)
        }
    }
}

class TitleView : UIView  {
    var label = ZMUtil.label(title: "违章信息", color: UIColor.zm.color666666(), font: UIFont.systemFont(ofSize: 16))
    override init(frame: CGRect) {
        super.init(frame: frame)
        setUI()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func setUI() {
        addSubview(label)
        backgroundColor = "#F1F2F5".zm.hex()
        label.snp.makeConstraints { make in
            make.top.left.equalToSuperview().offset(16)
        }
        snp.makeConstraints { make in
            make.height.equalTo(46)
        }
    }
}




protocol PayCheckerDelegate : NSObjectProtocol {
    func check(_ keepOn : @escaping (()->()))
}

class PayChecker<T> {
    
    weak var delegate : PayCheckerDelegate!
    
    var checkData : BehaviorRelay<T?> = BehaviorRelay(value: nil)
    
    var disposeBag = DisposeBag()
    
    var timerDisposeBag = DisposeBag()
        
    var timeOutTimes = 30
    
    var checkTimes = 0
    
    var keepOn = false
    
    var timer = Observable<Int>.timer(.seconds(0), period: .seconds(2), scheduler: MainScheduler.instance)
    
    // 开始轮询
    func startCheck() {
        keepOn = true
        checkTimes = 0
        realCheck()
    }
    
    // 停止轮询
    func stopCheck() {
        checkData.accept(nil)
        keepOn = false
    }
    
    func realCheck() {
        guard checkData.value != nil, keepOn else {return}
        if self.checkTimes >= timeOutTimes {
            stopCheck()
            return
        }
        keepOn = false
        self.delegate.check { [weak self] in
            guard let self = self else {return}
            self.keepOn = true
            self.checkTimes += 1
        }
    }
    
    init() {
        checkData.subscribe(onNext:{ [unowned self] resp in
            guard let _ = resp else {
                return
            }
            self.startCheck()
        }).disposed(by: disposeBag)
        
        timer.subscribe(onNext:{ [unowned self] resp in
            self.realCheck()
        }).disposed(by: timerDisposeBag)
    }
    
    deinit {
        XMLogger.info("PayChecker deinit")
    }
}
